package com.android.settings.audio.peq.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.view.View;

/**
 * Created by We on 2023/5/29
 */
public class ViewUtil {
    public static Bitmap saveViewAsBitmap(View view) {
        int width = view.getWidth();
        int height = view.getHeight();
        if (width <= 0 || height <= 0) {
            //android.util.Log.i("###", "size is unknown, maybe wrap_content, will measure");
            int specSize = View.MeasureSpec.makeMeasureSpec(0 /* any */, View.MeasureSpec.UNSPECIFIED);
            view.measure(specSize, specSize);
            width = view.getMeasuredWidth();
            height = view.getMeasuredHeight();
        }
        android.util.Log.i("###", "view size is w " + width + " h " + height);
        if (width <= 0 || height <= 0) {
            android.util.Log.e("###", "invalid size, do nothing, return null");
            return null;
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        if (view.getRight() <= 0 || view.getBottom() <= 0) {
            view.layout(0, 0, width, height);
            view.draw(canvas);
        } else {
            view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
            view.draw(canvas);
        }

        return bitmap;
    }
}
